<template>
  <div class="addgoods-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"> </el-alert>
      <el-steps :active="active-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- 左侧导航栏区域 -->
        <el-tabs tab-position="left" v-model="active" :before-leave="beforeTabLeave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label=" 商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader :options="categoriesList" :props="goodsProps" v-model="addForm.goods_cat" clearable
                @change="handleChange"> </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyParamList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="subItem" v-for="(subItem,index) in item.attr_vals" :key="index">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyParamList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :on-success="handleSuccess" :headers="headersObj" :action="uploadUrl" :on-preview="handlePreview"
              :on-remove="handleRemove" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
              <el-image :src="previewUrl" class="preImage"></el-image>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" />
            <el-button class="addBtn" type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
  import _ from 'lodash'
  export default {
    name: 'Add',
    data() {
      return {
        headersObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        uploadUrl: 'https://lianghj.top:8888/api/private/v1/upload',
        active: '0',
        addForm: {
          goods_name: '',
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          goods_cat: [],
          goods_introduce: '',
          pics: [],
          attrs: []
        },
        addFormRules: {
          goods_name: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }],
          goods_price: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }],
          goods_weight: [{
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }],
          goods_number: [{
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }],
          goods_cat: [{
            required: true,
            message: '请选择商品分类',
            trigger: 'blur'
          }]
        },
        categoriesList: [],
        goodsProps: {
          expandTrigger: 'hover',
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'
        },
        manyParamList: [],
        onlyParamList: [],
        previewUrl: '',
        dialogVisible: false
      }
    },
    created() {
      this.getCategoriesList()
    },
    computed: {
      categoriesId() {
        if (this.addForm.goods_cat.length === 3) {
          return this.addForm.goods_cat[2]
        }
        return null
      }
    },
    methods: {
      async getCategoriesList() {
        const {
          data: res
        } = await this.$http.get('categories')
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取商品分类失败',
            type: 'error'
          })
        } else {
          this.categoriesList = res.data
        }
      },
      handleChange(value) {
        if (this.addForm.goods_cat.length !== 3) {
          this.addForm.goods_cat = []
        }
      },
      beforeTabLeave(activeName, oldActiveName) {
        // console.log(activeName, oldActiveName)
        if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
          this.$message({
            type: 'error',
            message: '请选择商品分类'
          })
          return false
        }
      },
      tabClick() {
        if (this.active === '1') {
          this.getManyParamList()
        }
        if (this.active === '2') {
          this.getOnlyParamList()
        }
      },
      async getManyParamList() {
        const {
          data: res
        } = await this.$http.get(`categories/${this.categoriesId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取动态参数失败',
            type: 'error'
          })
        } else {
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
          })
          this.manyParamList = res.data
        }
      },
      async getOnlyParamList() {
        const {
          data: res
        } = await this.$http.get(`categories/${this.categoriesId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取静态属性失败',
            type: 'error'
          })
        } else {
          this.onlyParamList = res.data
        }
      },
      handleRemove(file, fileList) {
        const tmp_path = file.response.data.tmp_path
        const index = this.addForm.pics.findIndex(x => x.pic === tmp_path)
        this.addForm.pics.splice(index, 1)
      },
      handlePreview(file) {
        this.previewUrl = file.response.data.url
        this.dialogVisible = true
      },
      handleSuccess(response) {
        if (response.meta.status !== 200) {
          this.$message({
            type: 'error',
            message: '上传图片失败'
          })
        } else {
          const picInfo = {
            pic: response.data.tmp_path
          }
          this.addForm.pics.push(picInfo)
        }
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      },
      addGoods() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            this.$message({
              type: 'error',
              message: '请填写必要的表单项'
            })
          } else {
            this.manyParamList.forEach(item => {
              const newInfo = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(',')
              }
              this.addForm.attrs.push(newInfo)
            })
            this.onlyParamList.forEach(item => {
              const newInfo = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals
              }
              this.addForm.attrs.push(newInfo)
            })
            // 深拷贝lodash cloneDeep(obj)
            const addForm = _.cloneDeep(this.addForm)
            addForm.goods_cat = addForm.goods_cat.join(',')
            const {
              data: res
            } = await this.$http.post('goods', addForm)
            if (res.meta.status !== 201) {
              this.$message({
                showClose: true,
                message: '创建商品失败',
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: '创建商品成功',
                type: 'success'
              })
              this.$router.push('/goods')
            }
          }
        })
      }
    }
  }

</script>
<style lang="less" scoped>
  .box-card {
    margin-top: 15px;
    padding: 0;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;
  }

  .el-checkbox {
    margin: 0 10px 0 0 !important;
  }

  .preImage {
    width: 100%;
  }

  .addBtn {
    margin-top: 15px;
  }

</style>
